package com.woshengqile.service;

import net.hasor.core.Singleton;

import com.aliyuncs.DefaultAcsClient;
import com.aliyuncs.IAcsClient;
import com.aliyuncs.dm.model.v20151123.BatchSendMailRequest;
import com.aliyuncs.dm.model.v20151123.BatchSendMailResponse;
import com.aliyuncs.dm.model.v20151123.SingleSendMailRequest;
import com.aliyuncs.dm.model.v20151123.SingleSendMailResponse;
import com.aliyuncs.exceptions.ClientException;
import com.aliyuncs.exceptions.ServerException;
import com.aliyuncs.profile.DefaultProfile;
import com.aliyuncs.profile.IClientProfile;
import com.woshengqile.Setting;
import com.woshengqile.model.Mail;
import com.woshengqile.util.SystemUtils;

/**
 * 邮件
 * 
 * @author Think
 */
@Singleton
public class MailService {
	
	private IClientProfile iClientProfile;
	private IAcsClient iAcsClient;
	private Setting setting = SystemUtils.getSetting();
	
	public void singleSend(Mail mail) {
		SingleSendMailRequest request = new SingleSendMailRequest();
		// request.setVersion("2017-06-22");//
		// 如果是除杭州region外的其它region（如新加坡region）,必须指定为2017-06-22
		request.setAccountName(setting.getAliyunAccountName());
		request.setFromAlias(setting.getAliyunFromAlias());
		request.setAddressType(setting.getAliyunAddressType());
		request.setTagName(null);
		request.setReplyToAddress(true);
		request.setToAddress(mail.getMail());
		request.setSubject("测试邮件-我生气了注册验证码-来自阿里云推送");
		request.setHtmlBody("您的验证码是: 123456");
		try {
			SingleSendMailResponse httpResponse = getIAcsClient().getAcsResponse(request);
			httpResponse.getRequestId();
		} catch (ServerException e) {
			e.printStackTrace();
		} catch (ClientException e) {
			e.printStackTrace();
		}
	}
	
	public void batchSend() {
		BatchSendMailRequest request = new BatchSendMailRequest();
		request.setAccountName("yzc@mail.woshengqile.com");
		request.setAddressType(1);
		request.setTemplateName("模板名称");
		request.setReceiversName("收件人列表名称");
		request.setTagName("标签");
		try {
			BatchSendMailResponse httpResponse = getIAcsClient().getAcsResponse(request);
			httpResponse.getRequestId();
		} catch (ClientException e) {
			e.printStackTrace();
		}
	}
	
	private IAcsClient getIAcsClient() {
		if (iAcsClient == null) {
			iAcsClient = new DefaultAcsClient(getIClientProfile());
		}
		return iAcsClient;
	}
	
	private IClientProfile getIClientProfile() {
		if (iClientProfile == null) {
			// 如果是除杭州region外的其它region（如新加坡、澳洲Region），需要将下面的"cn-hangzhou"替换为"ap-southeast-1"、或"ap-southeast-2"。
			iClientProfile = DefaultProfile.getProfile(setting.getRegion(), setting.getAliyunAccessKey(), setting.getAliyunAccessSecret());
		}
		return iClientProfile;
	}

}
